package erz.printing.police.print;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;

import com.bumptech.glide.load.engine.Resource;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import erz.printing.police.R;
import erz.printing.police.settings.SettingPreferences;
import erz.printing.police.utils.ImageLoaderUtil;
//佳能iP110的水平和竖直dpi都是300
public class PhotoPrintAdapter extends PrintDocumentAdapter {
    private Context context;
    private PrintedPdfDocument myPdfDocument;
    private int totalPages;
    private int pageHeight;
    private int pageWidth;
    private float factor = 72.0f / 72.0f;

    private String title = "济南市公安局天桥区分局制锦市派出所";
    private String subTitle;
    private List<String> photos;

    private boolean bShowExaminer = false;
    private boolean bShowTitle = false;

    public PhotoPrintAdapter(Context context) {
        this.context = context;
        totalPages = 1;

        Resources res = context.getResources();
        int dpimax = res.getInteger(R.integer.photo_print_dpi_max);
        int dpimin = res.getInteger(R.integer.photo_print_dpi_min);
        SettingPreferences pref = new SettingPreferences(context);
        int dpi = pref.getInt(SettingPreferences.PHOTO_PRINT_DPI_KEY,
                res.getInteger(R.integer.photo_print_dpi_default));
        //
        factor = 72 + (300 - 72) * (dpi - dpimin)*1.0f / (dpimax - dpimin);
        factor = factor / 72.0f;
    }

    public void setShowExaminer(boolean show) {
        this.bShowExaminer = show;
    }

    public void setShowTitle(boolean show) {
        this.bShowTitle = show;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public void setPhotos(List<String> photos) {
        this.photos = photos;
    }

    @Override
    public void onLayout(PrintAttributes oldAttributes,
                         PrintAttributes newAttributes,
                         CancellationSignal cancellationSignal,
                         PrintDocumentAdapter.LayoutResultCallback callback,
                         Bundle metadata) {
        myPdfDocument = new PrintedPdfDocument(context, newAttributes);

        int vdpi = newAttributes.getResolution().getVerticalDpi();
        int hdpi = newAttributes.getResolution().getHorizontalDpi();
        // 单位72分之一英寸
        pageHeight =
                newAttributes.getMediaSize().getHeightMils()/1000 * 72;
        pageWidth =
                newAttributes.getMediaSize().getWidthMils()/1000 * 72;
        pageHeight *= factor;
        pageWidth *= factor;

        if (cancellationSignal.isCanceled()) {
            callback.onLayoutCancelled();
            return;
        }
        int contentType = PrintDocumentInfo.CONTENT_TYPE_DOCUMENT;
        totalPages = (int) Math.ceil(photos.size()*1.0f / 4);

        if (totalPages > 0) {
            PrintDocumentInfo.Builder builder = new PrintDocumentInfo
                    .Builder("print_firefight")
                    .setContentType(contentType);

            PrintDocumentInfo info = builder.build();
            callback.onLayoutFinished(info, true);
        } else {
            callback.onLayoutFailed("Page count is zero");
        }
    }

    @Override
    public void onWrite(final PageRange[] pageRanges,
                        final ParcelFileDescriptor destination,
                        final CancellationSignal cancellationSignal,
                        final PrintDocumentAdapter.WriteResultCallback callback) {
        for (int i = 0; i < totalPages; i++) {
            // 用户打印的时候可能选择不打印某些页，所以要这个判断
            if (pageInRange(pageRanges, i)) {
                PdfDocument.PageInfo newPage = new PdfDocument.PageInfo.Builder(pageWidth,
                        pageHeight, i).create();

                PdfDocument.Page page =
                        myPdfDocument.startPage(newPage);

                if (cancellationSignal.isCanceled()) {
                    callback.onWriteCancelled();
                    myPdfDocument.close();
                    myPdfDocument = null;
                    return;
                }
                drawPage(page, i);
                myPdfDocument.finishPage(page);
            }
        }

        try {
            myPdfDocument.writeTo(new FileOutputStream(
                    destination.getFileDescriptor()));
        } catch (IOException e) {
            callback.onWriteFailed(e.toString());
            return;
        } finally {
            myPdfDocument.close();
            myPdfDocument = null;
        }

        callback.onWriteFinished(pageRanges);
    }

    @Override
    public void onFinish() {
        super.onFinish();
    }

    private boolean pageInRange(PageRange[] pageRanges, int page) {
        for (int i = 0; i<pageRanges.length; i++) {
            if ((page >= pageRanges[i].getStart()) &&
                    (page <= pageRanges[i].getEnd()))
                return true;
        }
        return false;
    }

    //A4 210x297mm, 即595x842个单位
    private void drawPage(PdfDocument.Page page, int pagenumber) {
        Canvas canvas = page.getCanvas();

        int titleBaseLine = (int)(72*factor + 0.5f);//一个单位大概相当于0.353mm, 2.83个单位大概是1mm
        int leftMargin = (int)(54*factor + 0.5f);
        int bottomMargin = 54;

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        if (pagenumber == 0) {
            float lineHeight = 0.0f;
            if (bShowTitle) {
                paint.setTextSize(18*factor);
                Rect rect = new Rect();
                paint.getTextBounds(title, 0, title.length(), rect);
                int x = (pageWidth - rect.width()) / 2;
                canvas.drawText(title, x, titleBaseLine, paint);

                paint.setTextSize(14*factor);
                paint.getTextBounds(subTitle, 0, subTitle.length(), rect);
                x = (pageWidth - rect.width()) / 2;
                Paint.FontMetrics fm = paint.getFontMetrics();
                lineHeight = fm.bottom - fm.top + fm.leading;
                canvas.drawText(subTitle, x, titleBaseLine + lineHeight, paint);
            } else {
                paint.setTextSize(16*factor);
                Rect rect = new Rect();
                paint.getTextBounds(subTitle, 0, subTitle.length(), rect);
                int x = (pageWidth - rect.width()) / 2;
                canvas.drawText(subTitle, x, titleBaseLine + 8, paint);

                Paint.FontMetrics fm = paint.getFontMetrics();
                lineHeight = fm.bottom - fm.top + fm.leading;
            }

            float signHeight = lineHeight * 2;
            float photoBottom = bottomMargin + signHeight + lineHeight;//空白+签名区+加一行字高
            drawPhotos(canvas, paint,titleBaseLine + lineHeight*2, leftMargin,
                    pageWidth - leftMargin, pageHeight - photoBottom, getPhotosByPageNumber(pagenumber));

            drawSign(canvas, paint,pageHeight - photoBottom + lineHeight, leftMargin,
                    pageWidth - leftMargin, pageHeight - bottomMargin);
        } else {
            paint.setTextSize(14*factor);
            Paint.FontMetrics fm = paint.getFontMetrics();
            float lineHeight = fm.bottom - fm.top + fm.leading;

            float signHeight = lineHeight * 2;
            float photoBottom = bottomMargin + signHeight + lineHeight;//空白+签名区+加一行字高
            drawPhotos(canvas, paint, titleBaseLine, leftMargin,
                    pageWidth - leftMargin, pageHeight - photoBottom, getPhotosByPageNumber(pagenumber));

            drawSign(canvas, paint,pageHeight - photoBottom + lineHeight, leftMargin,
                    pageWidth - leftMargin, pageHeight - bottomMargin);
        }
    }

    private void drawPhotos(Canvas canvas, Paint paint, float top, float left, float right, float bottom, List<String> pagePhotos) {
        if (pagePhotos.size() == 1) {
            RectF rectF = new RectF(left, top, right, bottom);
            Bitmap bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(0), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();
        } else if (pagePhotos.size() == 2) {
            RectF rectF = new RectF(left, top, right, top + (bottom - top)/2 - 2*factor);
            Bitmap bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(0), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left, top + (bottom - top)/2 + 2*factor, right, bottom);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(1), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();
        } else if (pagePhotos.size() == 3) {
            RectF rectF = new RectF(left, top, left + (right - left)/2 - 2*factor, top + (bottom - top)/2 - 2*factor);
            Bitmap bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(0), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left + (right - left)/2 + 2*factor, top, right, top + (bottom - top)/2 - 2*factor);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(1), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left, top + (bottom - top)/2 + 2*factor, right, bottom);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(2), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();
        } else if (pagePhotos.size() == 4) {
            RectF rectF = new RectF(left, top, left + (right - left)/2 - 2*factor, top + (bottom - top)/2 - 2*factor);
            Bitmap bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(0), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left + (right - left)/2 + 2*factor, top, right, top + (bottom - top)/2 - 2*factor);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(1), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left, top + (bottom - top)/2 + 2*factor, left + (right - left)/2 - 2*factor, bottom);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(2), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();

            rectF = new RectF(left + (right - left)/2 + 2*factor, top + (bottom - top)/2 + 2*factor, right, bottom);
            bitmap = ImageLoaderUtil.getImageBitmap(pagePhotos.get(3), (int)rectF.width(), (int)rectF.height());
            drawFit(canvas, bitmap, 72, rectF);
            bitmap.recycle();
        }
    }

    private void drawSign(Canvas canvas, Paint paint, float top, float left, float right, float bottom) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        float lineHeight = fm.bottom - fm.top + fm.leading;
        float textHeight = fm.descent - fm.ascent;

        if (bShowExaminer) {
            canvas.drawText("检查人：", left, top + textHeight, paint);
            canvas.drawText("日期：", left, top + textHeight + lineHeight, paint);
        }

        canvas.drawText("当事人：", left + (right - left)*0.6f, top + textHeight, paint);
        canvas.drawText("日期：", left + (right - left)*0.6f, top + textHeight + lineHeight, paint);
    }

    private List<String> getPhotosByPageNumber(int pagenumber) {
        int start = pagenumber * 4;
        int end = pagenumber * 4 + 4;

        ArrayList<String> ret = new ArrayList<>();
        for (int i = 0; i < photos.size(); i++) {
            if (i >= start && i < end) {
                ret.add(photos.get(i));
            }
        }
        return ret;
    }

    private void drawFit(Canvas canvas, Bitmap bitmap, float ppi, RectF pageBounds) {
        //TODO: need to accept Gravity types for cropping (Center, East, West, etc..) - currently assumes North Gravity
        // 看情况旋转bitmap
        float bitmapRatio = bitmap.getWidth()*1.0f / bitmap.getHeight();
        float boundRatio = pageBounds.width()*1.0f / pageBounds.height();
        if ((bitmapRatio > 1.0f && boundRatio < 1.0f) || (bitmapRatio < 1.0f && boundRatio > 1.0f)) {
            Matrix matrix = new Matrix();
            matrix.postRotate(90);
            Bitmap tmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            bitmap = tmp;
        }
        float scale;
        float marginLeft =  0;//(float)margins.getLeftMils()/1000*ppi;
        float marginRight =  0;//(float)margins.getRightMils()/1000*ppi;
        float marginTop =  0;//(float)margins.getTopMils()/1000*ppi;
        float marginBottom =  0;//(float)margins.getBottomMils()/1000*ppi;

        float pageWidth = pageBounds.width() - (marginLeft + marginRight);
        float pageHeight = pageBounds.height() - (marginTop + marginBottom);

        float photoWidth = bitmap.getWidth();
        float photoHeight = bitmap.getHeight();

        if(pageWidth/photoWidth > pageHeight/photoHeight){
            scale = pageHeight/photoHeight;
        } else {
            scale = pageWidth/photoWidth;
        }

        photoWidth *= scale;
        photoHeight *= scale;

        final float left = pageBounds.left + (pageWidth - photoWidth)/2 + marginLeft;
        final float right = left + photoWidth;
        final float top = pageBounds.top + marginTop;
        final float bottom = top + photoHeight;

        canvas.drawBitmap(bitmap, null, new Rect((int) left, (int) top, (int) right, (int) bottom), null);
    }
}
